package com.sjm.suchbear.bluetoothtest;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.Utils;

import java.util.ArrayList;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CurveActivity extends Activity implements OnChartGestureListener, OnChartValueSelectedListener {

    @BindView(R.id.lc_LineChart)
    LineChart mLineChar;
    @BindView(R.id.tv_addData)
    TextView tvAddData;
    @BindView(R.id.tv_delete)
    TextView tvDelete;

    private LineDataSet set1;
    private ArrayList<Entry> values;
    private static int MAXSHOWPOINT = 7;
    private int xNow;
    private boolean start = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_curve);
        ButterKnife.bind(this);
        {
            //设置手势滑动事件
            mLineChar.setOnChartGestureListener(this);
            //设置数值选择监听
            mLineChar.setOnChartValueSelectedListener(this);
            //后台绘制
            mLineChar.setDrawGridBackground(false);
            //设置描述文本
            mLineChar.getDescription().setEnabled(false);
            //设置支持触控手势
            mLineChar.setTouchEnabled(true);
            //设置缩放
            mLineChar.setDragEnabled(true);
            //设置推动
            mLineChar.setScaleEnabled(true);
            //如果禁用,扩展可以在x轴和y轴分别完成
            mLineChar.setPinchZoom(true);
        }
        //这里我模拟一些数据
        values = new ArrayList<Entry>();

        xNow = 0;
        //设置数据
        setData(values);
        //默认动画
        mLineChar.animateX(250);
        //刷新
        mLineChar.invalidate();
        // 得到这个文字
        Legend l = mLineChar.getLegend();
        // 修改文字 ...
        l.setForm(Legend.LegendForm.LINE);


    }

    @SuppressLint("HandlerLeak")
    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Entry entry = (Entry) msg.obj;
            values.add(entry);
            setData(values);
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        start = true;
        AddRandomData addRandomData = new AddRandomData();
        addRandomData.start();
    }


    //传递数据集
    private void setData(ArrayList<Entry> values) {
        if (mLineChar.getData() != null && mLineChar.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) mLineChar.getData().getDataSetByIndex(0);
            set1.setValues(values);
            //set1.setDrawValues(true);
            mLineChar.getData().notifyDataChanged();
            mLineChar.notifyDataSetChanged();
            if (set1.getValues().size() > MAXSHOWPOINT) {
                float showMaxXRange = set1.getValues().get(set1.getValues().size() - 1).getX() - set1.getValues().get(set1.getValues().size() - MAXSHOWPOINT).getX();
                mLineChar.setVisibleXRangeMaximum(showMaxXRange);
                float moveX = set1.getValues().get(set1.getValues().size() - MAXSHOWPOINT).getX();
                mLineChar.moveViewToX(moveX);
            } else {
                mLineChar.moveViewToX(0);
            }
        } else {
            // 创建一个数据集,并给它一个类型
            set1 = new LineDataSet(values, "年度总结报告");

            // 在这里设置线
            set1.enableDashedLine(10f, 5f, 0f);
            set1.enableDashedHighlightLine(10f, 5f, 0f);
            set1.setColor(Color.BLACK);
            set1.setCircleColor(Color.BLACK);
            set1.setLineWidth(1f);
            set1.setCircleRadius(3f);
            set1.setDrawCircleHole(false);
            set1.setValueTextSize(9f);
            set1.setDrawFilled(true);
            set1.setFormLineWidth(1f);
            set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
            set1.setFormSize(15.f);
            //设置显示值
            set1.setDrawValues(true);
            set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);

            if (Utils.getSDKInt() >= 18) {
                // 填充背景只支持18以上
                //Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.ic_launcher);
                //set1.setFillDrawable(drawable);
                set1.setFillColor(Color.YELLOW);
            } else {
                set1.setFillColor(Color.BLACK);
            }
            ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
            //添加数据集
            dataSets.add(set1);

            //创建一个数据集的数据对象
            LineData data = new LineData(dataSets);

            //设置数据
            mLineChar.setData(data);
        }
    }

    private class AddRandomData extends Thread {
        @Override
        public void run() {
            super.run();
            while (start) {
                xNow = xNow + 5;
                Entry entry = new Entry(xNow, getRandom(0, 120));
                Message msg = new Message();
                msg.obj = entry;
                myHandler.handleMessage(msg);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static float getRandom(int min, int max) {
        Random random = new Random();
        int s = random.nextInt(max) % (max - min + 1) + min;
        return s;
    }


    @OnClick({R.id.tv_addData, R.id.tv_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_addData:
                start = true;
                AddRandomData addRandomData = new AddRandomData();
                addRandomData.start();
                break;
            case R.id.tv_delete:
                start = false;
                break;
        }
    }

    @Override
    public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {

    }

    @Override
    public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {

    }

    @Override
    public void onChartLongPressed(MotionEvent me) {

    }

    @Override
    public void onChartDoubleTapped(MotionEvent me) {

    }

    @Override
    public void onChartSingleTapped(MotionEvent me) {

    }

    @Override
    public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {

    }

    @Override
    public void onChartScale(MotionEvent me, float scaleX, float scaleY) {

    }

    @Override
    public void onChartTranslate(MotionEvent me, float dX, float dY) {

    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }


}
